package game.breeze.gameserver.message;

import game.breeze.Constants.Constants;
import game.breeze.socket.connection.MinaConnection;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class MessageHandler implements IoHandler {
	private int connectionCount;

	@Override
	public void exceptionCaught(IoSession session, Throwable arg1) throws Exception {
		sessionClosed(session);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		try {
			if (!(message instanceof IoBuffer)) {
				return;
			}
			MinaConnection conn = (MinaConnection) session.getAttribute(Constants.CONNECTION_KEY);
			IoBuffer buffer = (IoBuffer) message;
			int len = buffer.remaining();
			byte[] data = new byte[len];
			buffer.get(data, 0, data.length);
			buffer.free();
			conn.onDataRead(data, 0, len);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void messageSent(IoSession session, Object arg1) throws Exception {
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		connectionCount--;
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus arg1) throws Exception {
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		connectionCount++;
	}
}
